package com.amado.course41Annotation.homework;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/8/4.
 */
public class PrintAnnotataionValue {
	/**
	 * 之前的写法
	 * @param list
	 */
	public static void printOld(List<Goods> list) {
		if (list == null || list.isEmpty()) {
			return;
		}
		System.out.println("ID\t商品名称\t创建时间\t");
		for (int i = 0; i < list.size(); i++) {
			System.out.println(list.get(i).getId()+"\t"+list.get(i).getGoodsName()+"\t"+list.get(i).getCraeteTime());
		}
	}
	public static void print(List<?> list) {
		if (list == null || list.isEmpty()) {
			return;
		}
		for (int i = 0; i < list.size(); i++) {
			if (i == 0) {
				printHead(list.get(0));
			}
			printBody(list.get(0));
		}
	}

	public static void printHead(Object obj) {
		// 得到所有字段
		Field[] fields = obj.getClass().getDeclaredFields();
		for (Field field : fields) {
			// 得到个字段上的PrintAnnotation注解
			PrintAnnotation printAnnotation = field.getAnnotation(PrintAnnotation.class);
			// 没有注解就跳过
			if (printAnnotation == null) {
				continue;
			}
			System.out.print(printAnnotation.desc() + "\t");
		}
		System.out.println();
	}

	public static void printBody(Object obj) {
		Field[] fields = obj.getClass().getDeclaredFields();
		for (Field field : fields) {
			field.setAccessible(true);
			// 得到个字段上的PrintAnnotation注解
			try {
				System.out.print(field.get(obj)+"\t");
			} catch (IllegalArgumentException | IllegalAccessException e) {
				e.printStackTrace();
			}
		}
		System.out.println();
	}

	public static void main(String[] args) {
		List<Goods> listGoods = new ArrayList<>();
		listGoods.add(new Goods(1L, "商品1", "羽毛球", 20));
		listGoods.add(new Goods(2L, "商品2", "羽毛球1", 30));
		listGoods.add(new Goods(3L, "商品3", "羽毛球2", 40));
		
		
		List<GoodsCate> goodsCateList = new ArrayList<>();
		goodsCateList.add(new GoodsCate(1L, "商品1", "羽毛球"));
		goodsCateList.add(new GoodsCate(2L, "商品1", "羽毛球"));
		goodsCateList.add(new GoodsCate(3L, "商品1", "羽毛球"));
		
		printOld(listGoods);
		print(listGoods);
		print(goodsCateList);
	}
}
